import os
import psutil
import socket
import threading

class CreateServer(object):
    def __init__(self):
        super(CreateServer, self).__init__()
        self.host = self.get_ip()

    def runServer(self, port, buffer):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        sock.bind((self.host, port))
        sock.listen(50)
        print('servering listening')
        while True:
            try:
                client_sock, client_addr = sock.accept()
                recv = client_sock.recv(buffer)
                if recv:
                    print(recv)
            except Exception as runServer_ERR:
                print('runServer_ERR:',str(runServer_ERR))


    def get_ip(self,prefix='192.168.1.'):
        """
        通过给定前缀跨平台查询ip
        :param prefix:
        :return:
        """
        localIP = ''
        dic = psutil.net_if_addrs()
        for adapter in dic:
            snicList = dic[adapter]
            for snic in snicList:
                if not snic.family.name.startswith('AF_INET'):
                    continue
                ip = snic.address
                if ip.startswith(prefix):
                    localIP = ip
        return localIP

    def randomPort(self):
        pass




if __name__ == '__main__':
    hi_server=CreateServer()

    hi_server.runServer()